package com.example.gateway.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.json.JSONUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * [Sa-Token 权限认证] 配置类
 *
 * @author click33
 */

@Configuration
public class SaTokenConfigure {

    @Bean
    public SaReactorFilter getSaReactorFilter() {
        return new SaReactorFilter()
                .addInclude("/**")
                .addExclude("/favicon.ico", "/api/auth/captcha", "/api/swagger-ui/**",
                        "/api/v3/api-docs/**", "/api/druid/**", "/api/cache/**",
                        "/api/file/**", "/api/auth/register", "/api/auth/email/**",
                        "/api/auth/findpassword/**", "/demo/**")
                .setAuth(obj -> {
                    SaRouter.match("/**", "/api/auth/login", r -> StpUtil.checkLogin());
                })
                .setBeforeAuth(obj -> {
                    // 获取当前请求的Origin
                    String origin = SaHolder.getRequest().getHeader("Origin");

                    // 配置CORS响应头
                    SaHolder.getResponse()
                            .setHeader("Access-Control-Allow-Origin", origin)
                            .setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
                            // 显式列出允许的请求头（重点添加Authorization）
                            .setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
                            .setHeader("Access-Control-Max-Age", "3600")
                            // 允许跨域携带Cookie（如果前端需要）
                            .setHeader("Access-Control-Allow-Credentials", "true");

                    // 放行所有OPTIONS预检请求
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> {})
                            .back();
                })
                .setError(e -> {
                    SaHolder.getResponse()
                            .setHeader("Content-Type", "application/json;charset=UTF-8")
                            .setStatus(HttpStatus.UNAUTHORIZED.value());
                    return JSONUtil.toJsonStr(SaResult.error(e.getMessage()));
                });
    }
}
